package com.yizisu.basemvvm.utils.permission

import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.WindowManager
import androidx.core.app.ActivityCompat

internal class PermissionActivity : AppCompatActivity() {
    /**
     * 动态权限请求码，随意
     */
    private val needPermissionCode = 1234

    override fun onCreate(savedInstanceState: Bundle?) {
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
        super.onCreate(savedInstanceState)
        val permissions = PermissionUtil.requestPermissions
        if (permissions == null) {
            finish()
        } else {
            ActivityCompat.requestPermissions(this, permissions.toTypedArray(), needPermissionCode)
        }
    }

    /**
     * 处理请求的权限结果
     */
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == needPermissionCode) {
            val unGetPermissionList = mutableListOf<String>()
            grantResults.forEachIndexed { index, grantResult ->
                if (grantResult != PackageManager.PERMISSION_GRANTED) {
                    unGetPermissionList.add(permissions[index])
                }
            }
            PermissionUtil.permissionListener?.invoke(unGetPermissionList)
            PermissionUtil.permissionListener = null
            PermissionUtil.requestPermissions = null
            finish()
        }
    }
}
